#pragma once 
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

enum ErrorCode
{
    SUCCESS,
    FAIL
};
class UDP
{
public:
    UDP(int port)
        :m_ip("0.0.0.0")
        ,m_port(port)
    {}
    void Init()
    {
        // 创建套接字
        m_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (m_sockfd < 0)
        {
            std::cout << "创建套接字失败" << std::endl;
            exit(FAIL);
        }
        std::cout << "创建套接字成功" << std::endl;
        // bind套接字
        sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(m_port);
        inet_pton(AF_INET, m_ip.c_str(), &addr.sin_addr);
        int n = bind(m_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (n < 0)
        {
            std::cout << "绑定套接字失败" << std::endl;
            exit(FAIL);
        }
        std::cout << "绑定套接字成功" << std::endl;
    }
    void Start()
    {
        while (true)
        {
            // 接收消息
            char buffer[1024];
            sockaddr_in recv_addr;
            socklen_t len = sizeof(recv_addr);
            ssize_t n = recvfrom(m_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&recv_addr, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "接收成功: " << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "recvfrom 被关闭" << std::endl;
                exit(SUCCESS);
            }
            else 
            {
                std::cout << "接收异常" << std::endl;
                exit(FAIL);
            }
            // 响应
            std::string echo = "Echo #";
            echo += buffer;
            ssize_t m = sendto(m_sockfd, echo.c_str(), echo.size(), 0, (struct sockaddr *)&recv_addr, len);
            if (m < 0)
            {
                std::cout << "发送异常" << std::endl;
                exit(FAIL);
            }
            std::cout << "发送成功" << std::endl;
        }
    }
    ~UDP()
    {}
private:
    std::string m_ip;
    int m_port;
    int m_sockfd;
};